import { PerformanceMonitor } from './performance'

// 性能分析器
export class PerformanceAnalyzer {
    private static instance: PerformanceAnalyzer
    private monitor: PerformanceMonitor
    private analysisInterval: NodeJS.Timeout | null = null
    private reports: PerformanceReport[] = []

    private constructor() {
        this.monitor = PerformanceMonitor.getInstance()
        this.startAnalysis()
    }

    public static getInstance(): PerformanceAnalyzer {
        if (!PerformanceAnalyzer.instance) {
            PerformanceAnalyzer.instance = new PerformanceAnalyzer()
        }
        return PerformanceAnalyzer.instance
    }

    // 开始性能分析
    private startAnalysis(): void {
        // 每30秒生成一次性能报告
        this.analysisInterval = setInterval(() => {
            this.generateReport()
        }, 30000)
    }

    // 生成性能报告
    private generateReport(): PerformanceReport {
        const metrics = this.monitor.getAllMetrics()
        const memoryUsage = this.getMemoryUsage()
        const networkStats = this.getNetworkStats()

        const report: PerformanceReport = {
            timestamp: Date.now(),
            metrics,
            memoryUsage,
            networkStats,
            recommendations: this.generateRecommendations(metrics, memoryUsage),
            score: this.calculatePerformanceScore(metrics, memoryUsage)
        }

        this.reports.push(report)

        // 只保留最近100个报告
        if (this.reports.length > 100) {
            this.reports = this.reports.slice(-100)
        }

        return report
    }

    // 获取内存使用情况
    private getMemoryUsage(): MemoryUsage | null {
        if (typeof window === 'undefined' || !('memory' in performance)) {
            return null
        }

        const memory = (performance as any).memory
        return {
            usedJSHeapSize: memory.usedJSHeapSize,
            totalJSHeapSize: memory.totalJSHeapSize,
            jsHeapSizeLimit: memory.jsHeapSizeLimit,
            usedPercent: (memory.usedJSHeapSize / memory.jsHeapSizeLimit) * 100
        }
    }

    // 获取网络统计
    private getNetworkStats(): NetworkStats {
        if (typeof window === 'undefined') {
            return { totalRequests: 0, failedRequests: 0, averageResponseTime: 0 }
        }

        const entries = performance.getEntriesByType('navigation') as PerformanceNavigationTiming[]
        const resourceEntries = performance.getEntriesByType('resource') as PerformanceResourceTiming[]

        const totalRequests = resourceEntries.length
        const failedRequests = resourceEntries.filter(entry =>
            entry.transferSize === 0 && entry.decodedBodySize === 0
        ).length

        const responseTimes = resourceEntries
            .filter(entry => entry.responseEnd > entry.responseStart)
            .map(entry => entry.responseEnd - entry.responseStart)

        const averageResponseTime = responseTimes.length > 0
            ? responseTimes.reduce((sum, time) => sum + time, 0) / responseTimes.length
            : 0

        return {
            totalRequests,
            failedRequests,
            averageResponseTime
        }
    }

    // 生成性能建议
    private generateRecommendations(
        metrics: Record<string, any>,
        memoryUsage: MemoryUsage | null
    ): string[] {
        const recommendations: string[] = []

        // LCP 建议
        const lcpStats = metrics.LCP
        if (lcpStats && lcpStats.avg > 2500) {
            recommendations.push('LCP过高，建议优化图片加载和关键资源')
        }

        // FID 建议
        const fidStats = metrics.FID
        if (fidStats && fidStats.avg > 100) {
            recommendations.push('FID过高，建议减少主线程阻塞时间')
        }

        // CLS 建议
        const clsStats = metrics.CLS
        if (clsStats && clsStats.avg > 0.1) {
            recommendations.push('CLS过高，建议为图片和动态内容设置尺寸')
        }

        // 内存使用建议
        if (memoryUsage && memoryUsage.usedPercent > 80) {
            recommendations.push('内存使用率过高，建议清理未使用的数据和组件')
        }

        // API响应时间建议
        const apiStats = metrics.api_response_time
        if (apiStats && apiStats.avg > 1000) {
            recommendations.push('API响应时间过长，建议启用缓存或优化请求')
        }

        return recommendations
    }

    // 计算性能得分
    private calculatePerformanceScore(
        metrics: Record<string, any>,
        memoryUsage: MemoryUsage | null
    ): number {
        let score = 100

        // LCP 评分 (权重: 25%)
        const lcpStats = metrics.LCP
        if (lcpStats) {
            if (lcpStats.avg > 4000) score -= 25
            else if (lcpStats.avg > 2500) score -= 15
            else if (lcpStats.avg > 1200) score -= 5
        }

        // FID 评分 (权重: 25%)
        const fidStats = metrics.FID
        if (fidStats) {
            if (fidStats.avg > 300) score -= 25
            else if (fidStats.avg > 100) score -= 15
            else if (fidStats.avg > 50) score -= 5
        }

        // CLS 评分 (权重: 25%)
        const clsStats = metrics.CLS
        if (clsStats) {
            if (clsStats.avg > 0.25) score -= 25
            else if (clsStats.avg > 0.1) score -= 15
            else if (clsStats.avg > 0.05) score -= 5
        }

        // 内存使用评分 (权重: 25%)
        if (memoryUsage) {
            if (memoryUsage.usedPercent > 90) score -= 25
            else if (memoryUsage.usedPercent > 80) score -= 15
            else if (memoryUsage.usedPercent > 70) score -= 5
        }

        return Math.max(0, score)
    }

    // 获取最新报告
    public getLatestReport(): PerformanceReport | null {
        return this.reports.length > 0 ? this.reports[this.reports.length - 1] : null
    }

    // 获取历史报告
    public getReports(limit?: number): PerformanceReport[] {
        return limit ? this.reports.slice(-limit) : [...this.reports]
    }

    // 获取性能趋势
    public getPerformanceTrend(metric: string, timeRange = 30): TrendData {
        const recentReports = this.reports.slice(-timeRange)
        const values = recentReports
            .map(report => report.metrics[metric]?.avg)
            .filter(value => value !== undefined)

        if (values.length < 2) {
            return { trend: 'stable', change: 0, values: [] }
        }

        const firstValue = values[0]
        const lastValue = values[values.length - 1]
        const change = ((lastValue - firstValue) / firstValue) * 100

        let trend: 'improving' | 'degrading' | 'stable'
        if (Math.abs(change) < 5) {
            trend = 'stable'
        } else if (change < 0) {
            trend = 'improving'
        } else {
            trend = 'degrading'
        }

        return { trend, change, values }
    }

    // 导出性能数据
    public exportData(): PerformanceExport {
        return {
            timestamp: Date.now(),
            reports: this.reports,
            summary: this.generateSummary()
        }
    }

    // 生成性能摘要
    private generateSummary(): PerformanceSummary {
        if (this.reports.length === 0) {
            return {
                averageScore: 0,
                totalReports: 0,
                commonIssues: [],
                improvementAreas: []
            }
        }

        const scores = this.reports.map(report => report.score)
        const averageScore = scores.reduce((sum, score) => sum + score, 0) / scores.length

        // 统计常见问题
        const allRecommendations = this.reports.flatMap(report => report.recommendations)
        const recommendationCounts = allRecommendations.reduce((counts, rec) => {
            counts[rec] = (counts[rec] || 0) + 1
            return counts
        }, {} as Record<string, number>)

        const commonIssues = Object.entries(recommendationCounts)
            .sort(([, a], [, b]) => b - a)
            .slice(0, 5)
            .map(([issue, count]) => ({ issue, frequency: count }))

        // 改进建议
        const improvementAreas = this.generateImprovementAreas(commonIssues)

        return {
            averageScore,
            totalReports: this.reports.length,
            commonIssues,
            improvementAreas
        }
    }

    // 生成改进建议
    private generateImprovementAreas(commonIssues: Array<{ issue: string; frequency: number }>): string[] {
        const areas: string[] = []

        commonIssues.forEach(({ issue, frequency }) => {
            if (frequency > this.reports.length * 0.3) { // 如果问题出现频率超过30%
                if (issue.includes('LCP')) {
                    areas.push('优化首屏加载性能')
                } else if (issue.includes('FID')) {
                    areas.push('减少JavaScript执行时间')
                } else if (issue.includes('CLS')) {
                    areas.push('改善布局稳定性')
                } else if (issue.includes('内存')) {
                    areas.push('优化内存管理')
                } else if (issue.includes('API')) {
                    areas.push('优化网络请求')
                }
            }
        })

        return [...new Set(areas)] // 去重
    }

    // 清理分析器
    public cleanup(): void {
        if (this.analysisInterval) {
            clearInterval(this.analysisInterval)
            this.analysisInterval = null
        }
        this.reports = []
    }
}

// 类型定义
export interface PerformanceReport {
    timestamp: number
    metrics: Record<string, any>
    memoryUsage: MemoryUsage | null
    networkStats: NetworkStats
    recommendations: string[]
    score: number
}

export interface MemoryUsage {
    usedJSHeapSize: number
    totalJSHeapSize: number
    jsHeapSizeLimit: number
    usedPercent: number
}

export interface NetworkStats {
    totalRequests: number
    failedRequests: number
    averageResponseTime: number
}

export interface TrendData {
    trend: 'improving' | 'degrading' | 'stable'
    change: number
    values: number[]
}

export interface PerformanceExport {
    timestamp: number
    reports: PerformanceReport[]
    summary: PerformanceSummary
}

export interface PerformanceSummary {
    averageScore: number
    totalReports: number
    commonIssues: Array<{ issue: string; frequency: number }>
    improvementAreas: string[]
}

// React Hook for performance analysis
export function usePerformanceAnalyzer() {
    const analyzer = PerformanceAnalyzer.getInstance()

    const getLatestReport = () => analyzer.getLatestReport()
    const getReports = (limit?: number) => analyzer.getReports(limit)
    const getTrend = (metric: string, timeRange?: number) => analyzer.getPerformanceTrend(metric, timeRange)
    const exportData = () => analyzer.exportData()

    return {
        getLatestReport,
        getReports,
        getTrend,
        exportData
    }
}

// 全局性能分析器实例
export const performanceAnalyzer = PerformanceAnalyzer.getInstance()